/*
 * Created on2022/6/11 15:54
 *
 * Copyright(c) YuZhou Big Data Laboratory CO.,Ltd, 2022.  All rights reserved.
 *
 *******************************************************************************
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with
 * the License. You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 ******************************************************************************/

package org.yzbdl.lanius.core.plugins.metastore;

import java.sql.SQLException;
import java.util.List;

import org.yzbdl.lanius.core.exception.LaniusEngineDbException;
import org.yzbdl.lanius.core.metastore.HutoolDb;

import com.google.common.collect.Lists;

import cn.hutool.core.util.ArrayUtil;
import cn.hutool.db.Entity;
import cn.hutool.db.handler.BeanHandler;

/**
 * TODO
 *
 * @author hs@yzbdl.ac.cn
 * @version 1.0
 * @date 2019/6/11 15:54
 */
public class LdrClassificationDao {

    private static LdrClassificationDao ldrClassificationDao = new LdrClassificationDao();

    private LdrClassificationDao() {}

    public static LdrClassificationDao getInstance() {
        return ldrClassificationDao;
    }

    /**
     * 添加
     *
     * @param obj
     * @return
     * @throws LaniusEngineDbException
     */
    public LdrClassificationEntity save(LdrClassificationEntity obj) throws LaniusEngineDbException {
        try {
            Entity entity = Entity.create("ldr_classification").set("plugin_type_class", obj.getPluginTypeClass())
                .set("logic_type", obj.getLogicType()).set("name", obj.getName())
                .set("create_time", obj.getCreateTime()).set("sort_num", obj.getSortNum())
                .set("expanded", obj.getExpanded());
            Long id = HutoolDb.useDynamicUrlDb().insertForGeneratedKey(entity);
            obj.setId(id.intValue());
            return obj;
        } catch (SQLException e) {
            throw new LaniusEngineDbException(e);
        }
    }

    /**
     * 修改
     *
     * @param obj
     * @return
     * @throws LaniusEngineDbException
     */
    public LdrClassificationEntity update(LdrClassificationEntity obj) throws LaniusEngineDbException {
        try {
            Entity entity = Entity.create("ldr_classification").set("id", obj.getId())
                .set("plugin_type_class", obj.getPluginTypeClass()).set("logic_type", obj.getLogicType())
                .set("name", obj.getName()).set("create_time", obj.getCreateTime()).set("sort_num", obj.getSortNum())
                .set("expanded", obj.getExpanded());
            HutoolDb.useDynamicUrlDb().update(entity, Entity.create("ldr_classification").set("id", obj.getId()));
            return obj;
        } catch (SQLException e) {
            throw new LaniusEngineDbException(e);
        }
    }

    /**
     * 删除
     *
     * @param id
     */
    public void delete(Integer id) throws LaniusEngineDbException {
        try {
            HutoolDb.useDynamicUrlDb().del("ldr_classification", "id", id);
        } catch (SQLException e) {
            throw new LaniusEngineDbException(e);
        }
    }

    /**
     * 获取分类列表
     *
     * @param pluginTypeClass 插件类别类的名称: BasePluginType的子类类名全称
     * @return
     * @throws LaniusEngineDbException
     */
    public List<LdrClassificationEntity> getAll(String pluginTypeClass) throws LaniusEngineDbException {
        try {
            String sql = "select * from ldr_classification where plugin_type_class = ? order by sort_num asc";
            return HutoolDb.useDynamicUrlDb().query(sql, LdrClassificationEntity.class, pluginTypeClass);
        } catch (SQLException e) {
            throw new LaniusEngineDbException(e);
        }
    }

    /**
     * 根据插件类别, 逻辑类别查找, 返回所有
     *
     * @param pluginTypeClass 插件类别类的名称: BasePluginType的子类类名全称
     * @param logicType       逻辑类别, 1:常用, 2:自定义, 3:本地(默认), 4:云端(商店)
     * @return
     * @throws LaniusEngineDbException
     */
    public List<LdrClassificationEntity> getAll(String pluginTypeClass, int logicType) throws LaniusEngineDbException {
        try {
            String sql =
                "select * from ldr_classification where plugin_type_class = ? and logic_type = ? order by create_time desc";
            return HutoolDb.useDynamicUrlDb().query(sql, LdrClassificationEntity.class, pluginTypeClass, logicType);
        } catch (SQLException e) {
            throw new LaniusEngineDbException(e);
        }
    }

    /**
     * 根据pluginType类全名, 逻辑类别查找, 要求只能返回一条记录
     * 
     * @param pluginTypeClass 插件类别类的名称: BasePluginType的子类类名全称
     * @param logicType
     * @return
     * @throws LaniusEngineDbException
     */
    public LdrClassificationEntity getOne(String pluginTypeClass, Integer logicType) throws LaniusEngineDbException {
        try {
            return HutoolDb.useDynamicUrlDb().query(
                "select * from ldr_classification where plugin_type_class = ? and logic_type = ?",
                new BeanHandler<LdrClassificationEntity>(LdrClassificationEntity.class), pluginTypeClass, logicType);
        } catch (SQLException e) {
            throw new LaniusEngineDbException(e);
        }
    }

    /**
     * 根据插件类别, 逻辑类别查找, 要求只能返回一条记录
     *
     * @param pluginTypeClass 插件类别类的名称: BasePluginType的子类类名全称
     * @param logicType       逻辑类别, 1:常用, 2:自定义, 3:本地(默认), 4:云端(商店)
     * @return
     * @throws LaniusEngineDbException
     */
    public List<LdrClassificationEntity> getLeast(String pluginTypeClass, int logicType, int count)
        throws LaniusEngineDbException {
        try {
            String sql =
                "select * from ldr_classification where plugin_type_class = ? and logic_type = ? order by create_time desc limit 1";
            return HutoolDb.useDynamicUrlDb().query(sql, LdrClassificationEntity.class, pluginTypeClass, logicType);
        } catch (SQLException e) {
            throw new LaniusEngineDbException(e);
        }
    }

    /**
     * 获取自定义分组最大的排序号
     *
     * @param pluginTypeClass 插件类别类的名称: BasePluginType的子类类名全称
     * @return
     * @throws LaniusEngineDbException
     */
    public Integer getCustomizeMaxSortNum(String pluginTypeClass) throws LaniusEngineDbException {
        try {
            return HutoolDb.useDynamicUrlDb().query(
                "select max(sort_num) from ldr_classification where plugin_type_class = ? and logic_type = ?",
                new BeanHandler<Integer>(Integer.class), pluginTypeClass, LogicType.CUSTOMIZE.getId());
        } catch (SQLException e) {
            throw new LaniusEngineDbException(e);
        }
    }

    /**
     * 更新所有的展开状态
     *
     * @param expand
     * @throws LaniusEngineDbException
     */
    public void updateExpandStatus(boolean expand, Integer... ids) throws LaniusEngineDbException {
        try {
            List<Object> params = Lists.newArrayList();

            StringBuffer sql = new StringBuffer("update ldr_classification set expanded = ? ");
            params.add(expand);

            if (ids != null && ids.length > 0) {
                sql.append("where id in (");
                for (int i = 0; i < ids.length; i++) {
                    sql.append(" ?,");
                    params.add(ids[i]);
                }
                sql.deleteCharAt(sql.length() - 1);
                sql.append(" )");
            }

            HutoolDb.useDynamicUrlDb().execute(sql.toString(), ArrayUtil.toArray(params, Object.class));
        } catch (SQLException e) {
            throw new LaniusEngineDbException(e);
        }
    }

    /**
     * 根据主键Id查找
     * 
     * @param classificationId
     * @return
     * @throws LaniusEngineDbException
     */
    public LdrClassificationEntity getOne(Integer classificationId) throws LaniusEngineDbException {
        try {
            return HutoolDb.useDynamicUrlDb().query("select * from ldr_classification where id = ?",
                new BeanHandler<LdrClassificationEntity>(LdrClassificationEntity.class), classificationId);
        } catch (SQLException e) {
            throw new LaniusEngineDbException(e);
        }
    }

    /**
     * 
     * @param pluginTypeClassName
     * @return
     * @throws LaniusEngineDbException
     */
    public List<Entity> getEntitysBySql(String sql, Object... params) throws LaniusEngineDbException {
        try {
            return HutoolDb.useDb().query(sql, params);
        } catch (SQLException e) {
            throw new LaniusEngineDbException(e);
        }
    }

}
